# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 11:40:47 2018

生成实时电流环采集的数据，每2分钟采集一次，每次采集390个点的数据，时长为40ms
"""
import random
import numpy as np
import pymongo
import pandas as pd
import math
import datetime
from gov.data_process.data import DataProcess
from pao.data import string_to_date, process_db

# 每2分钟执行的数据处理
class DataProcessEvery2mins(DataProcess):
    def get_equip_ratio(self, date,dlh_num):
        #获取单一电流环连接的电器名字及其电流值的比值
        date = string_to_date(date)
        list_tep = []
        def process_func(db):
            nonlocal list_tep
            collection = db['analy_equip']
            t_H=date.hour
            dates=pd.date_range(date.strftime("%Y-%m-%d"),periods=25,freq='H')
            cxdate=dates[t_H]
            cur_tep=collection.find({'date':cxdate,'dlh_num':dlh_num})
            list_tep=list(cur_tep[:])
        process_db(self.db_addr, self.db_port, 'GovNetThing', process_func)

        df_tep=pd.DataFrame(list_tep)
        tep_sum=sum(df_tep['meanA'].tolist())
        df_tep['ratio']=df_tep.meanA/tep_sum
        res=df_tep[['ratio','equip_name']]
        return res

    def get_equip_ratio1(self, date,dlh_num):
        #获取单一电流环连接的电器名字及其电流值的比值
        date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
        client = pymongo.MongoClient(self.db_addr, self.db_port)
        db = client['GovNetThing']
        collection1=db['analy_equip']
        t_H=date.hour
        dates=pd.date_range(date.strftime("%Y-%m-%d"),periods=25,freq='H')
        cxdate=dates[t_H]
        client.close()
        cur_tep=collection1.find({'date':cxdate,'dlh_num':dlh_num})
        list_tep=list(cur_tep[:])
        df_tep=pd.DataFrame(list_tep)
        tep_sum=sum(df_tep['meanA'].tolist())
        df_tep['ratio']=df_tep.meanA/tep_sum
        res=df_tep[['ratio','equip_name']]
        return res

    def get_dlz(self, date_start,date_end,dlh_num):
        #获取单一电流环及时间对应的电流值
        date_start = datetime.datetime.strptime(date_start, "%Y-%m-%d %H:%M:%S")
        date_end = datetime.datetime.strptime(date_end, "%Y-%m-%d %H:%M:%S")   
        client = pymongo.MongoClient(self.db_addr, self.db_port)
        db = client['GovNetThing']
        collection1=db['shishidata_every_2mins']
        cur_tep=collection1.find({'dlh_num':dlh_num,'date':{'$gte':date_start,'$lt':date_end}})
        list_tep=list(cur_tep[:])
        client.close()
        df_tep=pd.DataFrame(list_tep)
        dlz=df_tep['mean_A'].iloc[0]
        res=round(dlz,2)
        return res   

    def get_dlh_list(self, fz,start_loc):
        #返回波形的数据，输入为峰值和波形开始的位置
        y=[fz*math.sin(x*2*math.pi/195) for x in range(start_loc,start_loc+390)]
        y_tep=map(lambda x : x if x >0 else 0 , y)
        y_res=[x for x in y_tep]
        #添加随机波动
        little=[fz*0.05*(random.random()+0.5) for x in range(390)]
        y_res1=np.array(y_res)+np.array(little)      
        return y_res1

    def get_equip_dlh_list(self, date_start,date_end,dlh_num):
        #生成电流环采集的总数据及电器数据，390个点
        #date_start='2018-12-12 13:53:59'
        #date_end='2018-12-12 13:55:59'
        #dlh_num=466117
        ratio_df=pd.DataFrame(columns=['ratio'])
        dlz_all=self.get_dlz(date_start,date_end,dlh_num)
        a1={'ratio':1,'equip_name':'实际电流值','dlz':dlz_all}
        a=pd.DataFrame.from_dict(a1,orient='index').T
        ratio_df=ratio_df.append(a,ignore_index=True)    
        ratio_df1=self.get_equip_ratio(date_start,dlh_num)    
        ratio_df1['dlz']=ratio_df1.ratio*dlz_all
        ratio_df=ratio_df.append(ratio_df1,ignore_index=True)
        columns_name=ratio_df.equip_name.tolist()
        datas=[]
        start_loc=random.randint(1,195)
        for i in columns_name:
            fz=ratio_df[ratio_df['equip_name']==i].dlz.iloc[0]
            data_list=self.get_dlh_list(fz,start_loc)
            datas.append(data_list)    
        res_df=pd.DataFrame({'equip_name':columns_name,'data':datas})
        res=res_df.to_json(orient='index',force_ascii=False)
        return res
